$(function () {
  if (!localStorage.getItem("token")) {
    layui.layer.msg("登录失败，token缺失", { icon: 5 }, function () {
      localStorage.removeItem("token");
      // 2. 强制跳转到登录页面
      window.parent.location.href = "/bigevent-end/login.html";
    });
  }

  var userid = location.search.replace("?", "");
  init();

  function init() {
    $.ajax({
      url: "/api/articlecate/" + userid,
      method: "get",
      success: function (res) {
        var img = res.data[0].cover_img;
        res.data[0].cover_img = null;
        layui.form.val("pubform", res.data[0]);
        $("#image").attr("src", "http://localhost:8888/uploads/" + img);
      },
    });
  }
  initEditor();
  var $image = $("#image");
  // 1.2 配置选项
  const options = {
    // 纵横比
    aspectRatio: 400 / 280,
    // 指定预览区域
    preview: ".img-preview",
  };

  // 1.3 创建裁剪区域
  $image.cropper(options);

  $("#btnChooseImage").on("click", function () {
    $("#coverFile").click();
  });

  $("#coverFile").on("change", function () {
    var file = $(this)[0].files;
    if (file.length === 0) layui.layer.msg("请选择文件");
    var imgurl = URL.createObjectURL(file[0]);
    $("#image").cropper("destroy").prop("src", imgurl).cropper(options);
  });

  $("#form-pub").on("submit", function (e) {
    e.preventDefault();
    var fd = new FormData($(this)[0]);

    pub(fd);
  });

  function pub(fd) {
    $.ajax({
      url: "/api/articlecate/" + userid,
      method: "post",
      data: fd,
      contentType: false,
      processData: false,
      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layui.layer.msg(res.message, { icon: 5 });
        }
        layui.layer.msg("编辑分类成功", { icon: 6 }, function () {
          window.parent.document.querySelector("#article").click();
        });
      },
    });
  }
});
